package com.mconnect.msurvey.controller;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.mconnect.msurvey.model.Responder;
import com.mconnect.msurvey.model.ResponderConfirm;
import com.mconnect.msurvey.model.ResponderRecommended;
import com.mconnect.msurvey.util.HibernateUtil;

public class ResponderManager extends HibernateUtil{
	
	public Responder confirmResponder(int id_responder, int idUser, String time, String date){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
       session.getTransaction().begin();
        
        Responder responder = (Responder) session.load(Responder.class, id_responder);
        responder.setConfirm("TAK");
        session.update(responder);
        
        ResponderConfirm confirm = new ResponderConfirm();
        confirm.setArrivalTime(time);
        Date arrivalDate = toSqlDate(date);
        confirm.setArrivalDate(arrivalDate);
        Timestamp confirmDate = new Timestamp(new java.util.Date().getTime());
        confirm.setConfirmDate(confirmDate);
        confirm.setConfirm_id_user(idUser);
        
        confirm.setId_responder(responder);
        
        session.save(confirm);
        
        session.getTransaction().commit();
       
		return responder;
	}
	
	public static java.sql.Date toSqlDate(String strDate)
    {
        DateFormat dateFrm = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date myDate = new java.util.Date();
        java.sql.Date sqlDate;

        try
        {
          myDate = dateFrm.parse(strDate);
          sqlDate = new java.sql.Date(myDate.getTime());
        }
        catch (Exception e)
        {
          sqlDate = null;
        }

        return (sqlDate);
    }
	
	@SuppressWarnings("unchecked")
	public List<Responder> getRespodnerById(int id_responder){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
        List<Responder> responder = new ArrayList<Responder>();
        responder = session.createQuery("from Responder where id_responder=" + id_responder).list();
        
        session.getTransaction().commit();
       
		return responder;
	}
	
	public Responder updateResponder(int id_responder){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
        
        Responder responder = (Responder) session.load(Responder.class, id_responder);
        responder.setConfirm("NOT");
        session.update(responder);
        
        session.getTransaction().commit();
       
		return responder;
	}
	
	public Responder getResponderById_recommend(int id_recommend){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		
		Responder responder = (Responder) session.createQuery("select s from Responder s LEFT JOIN s.recommendedList where id_recommended=" + id_recommend).uniqueResult();
		
		session.getTransaction().commit();
		return responder;
	}
	
	/**
	 * Metoda sprawdzajaca czy dana osoba wypelniala juz ankiete
	 * @return true - jezeli nikogo nie polecil <br>
	 * false - w przeciwnym wypadku
	 */
	public Boolean checkIfRecommendUserFillSurvey(int id_recommend){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
		
		boolean result = false;
		Query q = session.createSQLQuery("select id_recommended from responder_recommended where id_recommended = " + id_recommend + " and recConfirm='TAK'");
		
		if(q.list().isEmpty()){
			result = true;
		}
		session.getTransaction().commit();
		return result;
	}
	
	/**
	 * Zwraca id_uzytkownika ktory przeprowadzil ankiete
	 * @param id_responder
	 * @return
	 */
	public Integer getIdUserByIdResponder(int id_responder){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
		int id_user = (Integer) session.createSQLQuery("select DISTINCT id_userRecommend from survey where id_responder=" + id_responder).uniqueResult();
		
		session.getTransaction().commit();
		return id_user;
	}
	
	public String getConfirmByIdResponder(int id_responder){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	    
	    String confirm = (String) session.createSQLQuery("select confirm from responder where id_responder=" + id_responder).uniqueResult();
	    
	    session.getTransaction().commit();
		return confirm;
	}
	
	public Responder savePesel(int idResponder, int idConfirm, String pesel, int idUser){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	    
	    Responder responder = (Responder) session.load(Responder.class, idResponder);
	    responder.setPesel(pesel);
	    session.update(responder);
	    
	    ResponderConfirm confirm = (ResponderConfirm) session.load(ResponderConfirm.class, idConfirm);
	    Timestamp peselDate = new Timestamp(new java.util.Date().getTime());
	    confirm.setPeselDate(peselDate);
	    confirm.setPesel_id_user(idUser);
	    session.update(confirm);
	    
	    session.getTransaction().commit();
		return responder;
	}
	
	/**
	 * Sprawdza czy podany pesel istnieje w bazie danych
	 * @param pesel
	 * @return pesel : true - jezeli nie istnieje </br> pesel : false - w przeciwny wypadku
	 */
	public HashMap<String, String> checkPeselUnique(String pesel){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	    
	    HashMap<String, String> map = new HashMap<String, String>();
	    Query q = session.createQuery(" from Responder where pesel = '" + pesel + "'");
	    if(q.list().isEmpty()){
	    	map.put("pesel", "true");
	    }else{
	    	map.put("pesel", "false");
	    }
	    session.getTransaction().commit();
		return map;
	}
	
	public Responder saveNote(int idResponder, int idConfirm, String note, int idUser){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	    session.getTransaction().begin();
	    
	    Responder responder = (Responder) session.load(Responder.class, idResponder);
	    responder.setPesel("NIE");
	    responder.setNote(note);
	    session.update(responder);
	    
	    ResponderConfirm confirm = (ResponderConfirm) session.load(ResponderConfirm.class, idConfirm);
	    Timestamp peselDate = new Timestamp(new java.util.Date().getTime());
	    confirm.setPeselDate(peselDate);
	    confirm.setPesel_id_user(idUser);
	    session.update(confirm);
	    
	    session.getTransaction().commit();
		return responder;
	}
	
	public Responder saveRecommendInConfirmPanel(int id_responder, int idConfirm,  String [] recommendFirstname, String [] recommendedLastname, String [] recommendedPhone, String [] recommendedMail){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.getTransaction().begin();
        
        Responder responder = (Responder) session.load(Responder.class, id_responder);
        List<ResponderRecommended> recommendedList = responder.getRecommendedList();
        for(int i=0; i<=recommendFirstname.length -1; i++){
        	if(!recommendFirstname[i].isEmpty() && !recommendedLastname[i].isEmpty() && !recommendedPhone[i].isEmpty()){
        		ResponderRecommended recommend = new ResponderRecommended();
        		recommend.setFirstName(recommendFirstname[i]);
        		recommend.setLastName(recommendedLastname[i]);
        		if(!recommendedMail[i].isEmpty()){
        			recommend.setMail(recommendedMail[i]);
        		}
        		recommend.setPhone(Integer.parseInt(recommendedPhone[i]));
            	recommendedList.add(recommend);
        	}
        	
        }
        responder.setRecommendedList(recommendedList);
        //responder.setNumberOfRecommend(recommendedList.size());
        session.update(responder);      
        ResponderConfirm confirm = (ResponderConfirm) session.load(ResponderConfirm.class, idConfirm);
        confirm.setNumberOfRecommendConfirm(confirm.getNumberOfRecommendConfirm() +  (recommendFirstname.length -1));
        session.getTransaction().commit();
		return responder;
	}
	
//	public static void main(String[] args) {
//		ResponderManager rM = new ResponderManager();
//		//rM.saveRecommendInConfirmPanel(10);
//	}

}
